import uuid
import datetime

from src.Business.table.tableBase import TableBase
from origanization.serializer import CourseTaskSerializer, CourseTaskRushSerializer
from common.models import TbCourseTask, TbMiniappUser, TbCourseTaskRush


class CourseTaskFactory(TableBase):
    def create_course_task(self, **kwargs):
        """
        创建课程任务
        """
        user: TbMiniappUser = kwargs.get("user")
        course_task_info = super().add_record(user=user)
        course_task_info["organization_id"] = user.organization_id
        course_task_info["is_prepayment"] = 0
        course_task_info["stage"] = 0
        for k, v in kwargs.items():
            course_task_info[k] = v
        course_task_info["state"] = 10
        course_task_ser = CourseTaskSerializer(data=course_task_info)
        if course_task_ser.is_valid():
            return course_task_ser.save()
        else:
            raise ValueError(course_task_ser.errors)

    def update_course_task(self, **kwargs):
        """
        修改课程任务信息
        """
        course_task_id = kwargs.get("course_task_id")
        user = kwargs.get("user")
        try:
            course_task = TbCourseTask.objects.get(uid=course_task_id)
        except TbCourseTask.DoesNotExist:
            raise ValueError("未找到该课程任务")
        kwargs["update_user"] = user.username
        kwargs["update_user_id"] = user.uid
        kwargs["uid"] = course_task_id
        course_task_ser = CourseTaskSerializer(instance=course_task, data=kwargs)
        if course_task_ser.is_valid():
            return course_task_ser.save()
        else:
            raise ValueError(str(course_task_ser.errors))

    def rush_course_task(self, **kwargs):
        """
        抢单
        """
        user: TbMiniappUser = kwargs.get("user")
        course_task_id = kwargs.get("course_task_id")
        teacher = user.teacher
        rush_record_info = super().add_record(user=user)
        rush_record_info["teacher_id"] = teacher.uid
        rush_record_info["course_task_id"] = course_task_id
        rush_record_info["rush_time"] = datetime.datetime.now()
        rush_ser = CourseTaskRushSerializer(data=rush_record_info)
        if rush_ser.is_valid():
            return rush_ser.save()
        else:
            raise ValueError(str(rush_ser.errors))
